package com.tcode.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.User;
import org.codehaus.jackson.map.ObjectMapper;

import com.tcode.bean.PrivilegeBean;
import com.tcode.bean.RoleBean;
import com.tcode.bean.UserBean;
import com.tcode.service.DeptService;
import com.tcode.service.UserService;
import com.tcode.utils.BeanFactory;
import com.tcode.utils.Page;
import com.tcode.utils.WriterUtil;

/**
 * Servlet implementation class InitServlet
 */
@WebServlet({"/InitServlet","/UserServlet"})
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	UserService us = (UserService) BeanFactory.getBean("UserService");
	DeptService ds = (DeptService) BeanFactory.getBean("deptService");
//	UserService us = new UserService();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    
    public void login(HttpServletRequest request, HttpServletResponse response){
    	String username =request.getParameter("userName");
		String pwd =request.getParameter("password");
		
		UserBean user = new UserBean();
		user.setName(username);
		user.setPhone(pwd);
		try {
			if(us.getUserCount(user)){
//				request.setAttribute("username", username);
				UserBean u =us.getUserInfo(user);
				request.getSession().setAttribute("user", u);
				List<PrivilegeBean> list =us.getRolePrivilege(u.getId());
				for (PrivilegeBean privilegeBean : list) {
					System.out.println(privilegeBean.getParentName());
				}
				request.getSession().setAttribute("menu", list);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}else{
				request.setAttribute("errorTip", "用户名密码有误");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			request.getRequestDispatcher("404.jsp").forward(request, response);
		}
    }
    
    
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    	try {
			
    		
    		
//    		System.out.println(us.searchUser());
//			request.setAttribute("list", us.searchUser());
//			request.getRequestDispatcher("404.jsp").forward(request, response);
			
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    	
    	
//    	ObjectMapper om = WriterUtil.writeTopage();
//    	try {
////    		request.setAttribute("list", us.searchUser());
//    		UserBean user =new UserBean();
//    		user.setId(0011);
////    		user.setName("zxd");
//    		user.setDeptName("tttt");
//    		user.setPhone("110");
//    		Page<UserBean> pages =us.getUserList(user, 1, 5);
//			om.writeValue(response.getOutputStream(), pages);
//			
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    }
    
    public void register(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	String userName =request.getParameter("username").trim();
    	String pwd =request.getParameter("password").trim();
    	Map<String, String> map = new HashMap<String,String>();
    	//首先我们要拿着username去后台查询这个东西是不是已经存在了，如果存在，我们要返回数据给前台页面说用户名已存在。
    	UserBean u =new UserBean();
    	u.setName(userName);
    	u.setPhone(pwd);
    	ObjectMapper om =WriterUtil.writeTopage();
    	if(us.getUserCountIfExist(u)) {
    		
        	try {
    			if(us.addUser(u)){
    				map.put("flag", "1");
    			}else{
    				map.put("flag", "0");
    			}
    			
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			map.put("flag", "-1");
    		}
    	}else {
    		map.put("flag", "2");
    		map.put("msg", "用户已存在");
    	}
		om.writeValue(response.getOutputStream(), map);
		
	}
    
    
    public void getAllUser(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	
    	int pageNo =Integer.parseInt(request.getParameter("pageNo").trim());
    	int pageSize =Integer.parseInt(request.getParameter("pageSize").trim());
    	
    	UserBean u = new UserBean();
    	
    	Page<UserBean> pages =us.getUserList(u, pageNo, pageSize);
    	ObjectMapper om = WriterUtil.writeTopage();
    	Map<String, Object> map = new HashMap<String,Object>();
    	map.put("msg", pages);
    	
    	om.writeValue(response.getOutputStream(), map);
    	
    }
    
    public void changeUser(HttpServletRequest request, HttpServletResponse response)throws Exception{
    	String userName =request.getParameter("username").trim();
    	String pwd =request.getParameter("password").trim();
    	String id =request.getParameter("id").trim();
    	String deptid =request.getParameter("deptid").trim();
    	UserBean u =new UserBean();
    	u.setId(Integer.parseInt(id));
    	u.setDeptId(Integer.parseInt(deptid));
    	u.setName(userName);
    	u.setPhone(pwd);
    	ObjectMapper om = WriterUtil.writeTopage();
    	Map<String, String> map = new HashMap<String,String>();
		try {
			if(us.updateUser(u)){
				map.put("flag", "1");
			}else{
				map.put("flag", "0");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("flag", "-1");
		}
		om.writeValue(response.getOutputStream(), map);
    }
    
    public void getRoleList(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	UserBean user =(UserBean) request.getSession().getAttribute("user");
    	ObjectMapper om =WriterUtil.writeTopage();
    	Map<String, Object> map = new HashMap<String, Object>();
    	System.out.println("==================="+user);
    	try {
			map.put("allRole", us.getAllRole());
			map.put("userRole",us.getRoleByUserid(user.getId()));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	om.writeValue(response.getOutputStream(), map);
    	
    }
    
    public void addUserRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	
    	UserBean user =(UserBean) request.getSession().getAttribute("user");
    	String roleid =request.getParameter("roleid");
    	ObjectMapper om =WriterUtil.writeTopage();
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("flag","0");
    	RoleBean role = new RoleBean();
    	role.setUserid(user.getId());
    	role.setId(Integer.parseInt(roleid));
    	
    	try {
			if(us.insertUserRole(role)) {
				map.put("flag","1");
				List<PrivilegeBean> list =us.getRolePrivilege(user.getId());
				request.getSession().setAttribute("menu", list);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println("添加");
    	om.writeValue(response.getOutputStream(), map);
    }
    public void delUserRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	
    	UserBean user =(UserBean) request.getSession().getAttribute("user");
    	String roleid =request.getParameter("roleid");
    	
    	ObjectMapper om =WriterUtil.writeTopage();
    	
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("flag","0");
    	RoleBean role = new RoleBean();
    	role.setUserid(user.getId());
    	role.setId(Integer.parseInt(roleid));
    	
    	
    	try {
			if(us.delUserRole(role)) {
				map.put("flag","1");
				List<PrivilegeBean> list =us.getRolePrivilege(user.getId());
				request.getSession().setAttribute("menu", list);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println("删除");
    	
    	om.writeValue(response.getOutputStream(), map);
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		String method =request.getParameter("_method");
		
		if("login".equals(method)){
			login(request, response);
		}else if("register".equals(method)){
			try {
				register(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("getAllUser".equals(method)){
			try {
				getAllUser(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("update".equals(method)){
			try {
				changeUser(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("role".equals(method)) {
			getRoleList(request, response);
		}else if("addrole".equals(method)) {
			addUserRole(request, response);
		}else if ("delRole".equals(method)){
			delUserRole(request, response);
		}else {
			System.out.println("else===========================");
			getAll(request, response);
		}
	}
	
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
